import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import { clearResultsAction, getResultsAction } from '@/store/action/search';
import { InfiniteScroll, Toast } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult() {
  const location = useLocation();
  const search = new URLSearchParams(location.search);
  const q = search.get('q');

  const { resultData } = useAppSelector((state) => state.search);
  const { results, page } = resultData;
  const dispatch = useDispatch();
  useEffect(() => {
    if (!q) {
      Toast.show({ content: '搜索关键字不能为空' });
      return;
    }
    dispatch(getResultsAction(q));
  }, [q, dispatch]);

  useEffect(() => {
    return () => {
      dispatch(clearResultsAction());
    };
  }, [dispatch]);

  const loadMore = async () => {
    await dispatch(getResultsAction(q as string, page + 1));
  };

  return (
    <div className={styles.root}>
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {results.map((item) => (
          <ArticleItem key={item.art_id} data={item} />
        ))}
      </div>
      {!!results.length && (
        <InfiniteScroll loadMore={loadMore} hasMore={results.length !== resultData.total_count} />
      )}
    </div>
  );
}
